/***************************************************************************
 *   Copyright (C) 2009 by Zheng Yonglei
 *   zhengyonglei@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "BrowseWordsWidget.h"

BrowseWordsWidget::BrowseWordsWidget(QWidget *parent)
    : QWidget(parent),
    mBrowseDirecton(BD_none),
    mHasUntouched(true),
    mStartBrowse(false)
{
	ui.setupUi(this);

	ui.browseWordIndexBar->setEnabled(false);
	ui.customListEdit->setInputMask("999");
	initConnections();

	mBrowsePreviousShortcut = new QShortcut(QKeySequence(Qt::Key_A),  this);
	QObject::connect(mBrowsePreviousShortcut,SIGNAL(activated()),this,SLOT(browsePreviousWord()));

	mBrowseNextShortcut = new QShortcut(QKeySequence(Qt::Key_D),  this);
	QObject::connect(mBrowseNextShortcut,SIGNAL(activated()),this,SLOT(browseNextWord()));

	/*mScrollUpShortcut = new QShortcut(QKeySequence(Qt::Key_J),  this);
	QObject::connect(mScrollUpShortcut,SIGNAL(activated()),this,SLOT(browserScrollUp()));

	mScrollDownShortcut = new QShortcut(QKeySequence(Qt::Key_K),  this);
	QObject::connect(mScrollDownShortcut,SIGNAL(activated()),this,SLOT(browserScrollDown()));
*/
	mSetCustomListShortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return),  this);
	QObject::connect(mSetCustomListShortcut,SIGNAL(activated()),this,SLOT(updateCustomListInfo()));

	ui.skipFinishedCheckBox->setChecked(OPT.skipFinishedWords);
	ui.browseDisplayArea->showNavList();
}

BrowseWordsWidget::~BrowseWordsWidget()
{
	cout<<"BrowseWordsWidget::~BrowseWordsWidget()"<<endl;
}

void BrowseWordsWidget::initConnections()
{
	QObject::connect(ui.browseNexButton, SIGNAL(clicked()), this, SLOT(browseNextWord()));
	QObject::connect(ui.browsePreviousButton, SIGNAL(clicked()), this, SLOT(browsePreviousWord()));
	QObject::connect(ui.browseWordIndexBar, SIGNAL(valueChanged(int)), ui.wordIndexSpinBox, SLOT(setValue(int)));
	QObject::connect(ui.wordIndexSpinBox, SIGNAL(valueChanged(int)), ui.browseWordIndexBar, SLOT(setValue(int)));
	QObject::connect(ui.wordIndexSpinBox, SIGNAL(valueChanged(int)), this, SLOT(browseWordByIndex(int)));
	//QObject::connect(ui.browseWordTabSpeakButton, SIGNAL(clicked()), this, SLOT(speakButtonClicked()));

	mSpeakShortcut = new QShortcut(QKeySequence(Qt::Key_S),  this);
	QObject::connect(mSpeakShortcut,SIGNAL(activated()),this,SLOT(speakButtonClicked()));

	QObject::connect(ui.setCustomList,SIGNAL(clicked()),this,SLOT(updateCustomListInfo()));

	QObject::connect(ui.skipFinishedCheckBox,SIGNAL(clicked()),this,SLOT(setSkipFinishedCheckBoxVal()));
}
/*
void BrowseWordsWidget::browserScrollUp()
{
	QScrollBar* vBar = ui.browseDisplayArea->verticalScrollBar();
	int curValue = vBar->value();
	curValue = curValue + vBar->singleStep()*3;
	vBar->setValue(curValue);
}

void BrowseWordsWidget::browserScrollDown()
{
	QScrollBar* vBar = ui.browseDisplayArea->verticalScrollBar();
	int curValue = vBar->value();
	curValue = curValue - vBar->singleStep()*3;
	vBar->setValue(curValue);
}
*/
void BrowseWordsWidget::initWordBrowserTask()
{
	cout<<"BrowseWordsWidget::initWordBrowserTask"<<endl;
	mStartBrowse = false;
	int browseWordSliderMax = WM.getListWordCount() - 1;
	cout<<"BrowseWordsWidget::initWordBrowserTask-->browseWordSliderMax="<<browseWordSliderMax<<endl;
	ui.browseWordIndexBar->setValue(0);
	ui.browseWordIndexBar->setMaximum(browseWordSliderMax);
	ui.browseWordIndexBar->setMinimum(0);
	ui.wordIndexSpinBox->setMaximum(browseWordSliderMax);
	ui.wordIndexSpinBox->setMinimum(0);

	cout<<"BrowseWordsWidget::initWordBrowserTask-->getActiveWordTotalFinishedCount="<<WM.getActiveWordTotalFinishedCount()<<endl;
	cout<<"BrowseWordsWidget::initWordBrowserTask-->getActiveWordCount="<<WM.getActiveWordCount()<<endl;
	if(WM.getActiveWordTotalFinishedCount() == WM.getActiveWordCount())
	{
		mHasUntouched = false;
		//cout<<"BrowseWordsWidget::initWordBrowserTask-->mHasUntouched="<<mHasUntouched<<endl;
		//exit(0);
	}
	else
	{
		mHasUntouched = true;
		//cout<<"BrowseWordsWidget::initWordBrowserTask-->mHasUntouched="<<mHasUntouched<<endl;
	}

	ui.wordIndexSpinBox->setValue(0);
	mStartBrowse = true;
	browseWordByIndex(-1);
}

void BrowseWordsWidget::changeWordId(int id)
{
	cout<<"BrowseWordsWidget::changeWordId("<<id<<")"<<endl;
	WM.setCurWordId(id-1);
}

void BrowseWordsWidget::browseNextWord()
{
	mBrowseDirecton = BD_Next;
	int curIndex = ui.wordIndexSpinBox->value();
	curIndex++;
	//cout<<"DisplayArea::browsePreviousWord-->curIndex="<<curIndex<<endl;
	//ui.wordIndexSpinBox->setValue(curIndex);
	if (curIndex >= WM.getListWordCount()-1)
		ui.wordIndexSpinBox->setValue(0);
	else
		ui.wordIndexSpinBox->setValue(curIndex);
}

void BrowseWordsWidget::browsePreviousWord()
{
	mBrowseDirecton = BD_Previous;
	int curIndex = ui.wordIndexSpinBox->value();
	curIndex--;
	//cout<<"DisplayArea::browsePreviousWord-->curIndex="<<curIndex<<endl;
	//ui.wordIndexSpinBox->setValue(curIndex);
	if (curIndex <= -1)
		ui.wordIndexSpinBox->setValue(WM.getListWordCount()-1);
	else
		ui.wordIndexSpinBox->setValue(curIndex);
}

void BrowseWordsWidget::browseWordByIndex(int index)
{
	if (mStartBrowse)
	{
		if (index == -1)
		{
			index = WM.getCurWordIndexByID(WM.getCurWordID());
			cout<<"BrowseWordsWidget::browseWordByIndex-->WM.getCurWordID()="<<WM.getCurWordID()<<endl;
			cout<<"BrowseWordsWidget::browseWordByIndex-->index = "<<index<<endl;
		}
		if (index == -1)
			index = 0;
		OPT.lockSwitchTask = false;

		WM.browseWordByIndex(index);
		DM.lookup(WM.getCurWord());

		ui.browseDisplayArea->showNavList();
		OPT.lockArticleNav = false;
		OPT.lockSpeak = false;
		OPT.lockWordBrowserSearch = false;
		if (ui.skipFinishedCheckBox->isChecked() && mHasUntouched)
		{
			if (WM.getCurWord()->getWordStatus() == WS_Untouched)
			{
				//ui.browseDisplayArea->getTextBrowser()->clear();
				//ui.browseDisplayArea->clearDisplay();
				//ui.browseDisplayArea->showEnglish();
				//ui.browseDisplayArea->showSoundMark();
				//ui.browseDisplayArea->showAllExplanations();
				BrowseForm history(-1, QString(), QString(), QString(), HT_Browse);
				ui.browseDisplayArea->showAll(history, false);
				//ui.browseDisplayArea->display();
				showWordHistoryInfo();
				showCustomListInfo();
				ui.wordIndexSpinBox->setValue(WM.getCurWordIndex());
			}
			else
			{
				if (mBrowseDirecton == BD_Next)
					browseNextWord();
				else
					browsePreviousWord();
			}
		}
		else
		{
			//WM.browseWordByIndex(index);
			//ui.browseDisplayArea->getTextBrowser()->clear();
			//ui.browseDisplayArea->clearDisplay();
			//ui.browseDisplayArea->showEnglish();
			//ui.browseDisplayArea->showSoundMark();
			//ui.browseDisplayArea->showAllExplanations();
			//ui.browseDisplayArea->display();
			BrowseForm history(-1, QString(), QString(), QString(), HT_Browse);
			ui.browseDisplayArea->showAll(history, false);
			//ui.browseDisplayArea->showAll();
			showWordHistoryInfo();
			showCustomListInfo();
			ui.wordIndexSpinBox->setValue(WM.getCurWordIndex());
		}
	}
}

void BrowseWordsWidget::speakButtonClicked()
{
	ui.browseDisplayArea->speak();
}

void BrowseWordsWidget::showWordHistoryInfo()
{
	ui.wordHistoryDisplay->clear();
	int reciteCount = WM.getCurWord()->getTotalReciteCount();
	QString reciteCountString;
	if (reciteCount == 0)
		reciteCountString = QString("Recite count: <FONT COLOR=red>%1</FONT>.").arg(reciteCount);
	else
		reciteCountString = QString("Recite count: %1.").arg(reciteCount);
	ui.wordHistoryDisplay->insertHtml(reciteCountString + "<br>");
	QStringList reciteDateList =  WM.getCurWord()->getReciteDateString();
	ui.wordHistoryDisplay->insertHtml("Recite date: <br>");
	for (int i=0; i<reciteDateList.size(); i++)
		ui.wordHistoryDisplay->insertHtml(reciteDateList[i] + "<br>");
	ui.wordHistoryDisplay->insertHtml(QString("GPR: %1.<br>").arg(WM.getCurWord()->getGrossPassRate()));

	QString queryCommand;
	queryCommand = QString("select id,custom_list,red_bible_list from lists where id=%1;").arg(WM.getCurWord()->getID());
	DB.execQuery(queryCommand, QueryT_Read, DB.mUsrMain);
	QString customList = DB.getTableValue(0,"custom_list");
	QString redBibleList = DB.getTableValue(0,"red_bible_list");
	ui.wordHistoryDisplay->insertHtml("Location: <br>");
	ui.wordHistoryDisplay->insertHtml(QString("Red Bible: %1.<br>").arg(redBibleList));
	ui.wordHistoryDisplay->insertHtml(QString("Custom List: %1.<br>").arg(customList));
}

void BrowseWordsWidget::showCustomListInfo()
{
	QString queryCommand;
	queryCommand = QString("select id,custom_list from lists where id=%1;").arg(WM.getCurWord()->getID());
	DB.execQuery(queryCommand, QueryT_Read, DB.mUsrMain);
	QString customList = DB.getTableValue(0,"custom_list");

	if (customList != "0")
	{
		ui.customListEdit->setText(customList);
	}
	else
	{
		queryCommand = "select max(custom_list) from lists;";
		DB.execQuery(queryCommand, QueryT_Read, DB.mUsrMain);
		int maxCustomList = DB.getTableValue(0,"max(custom_list)").toInt();
		//maxCustomList++;
		ui.customListEdit->setText(QString("%1").arg(maxCustomList));
	}
}

void BrowseWordsWidget::updateCustomListInfo()
{
	QString queryCommand;
	int listID = ui.customListEdit->text().toInt();
	queryCommand = QString("update lists set custom_list=%1").arg(listID);
	queryCommand.append(QString(" where id = %1;").arg(WM.getCurWord()->getID()));
	DB.execQuery(queryCommand, QueryT_Write, DB.mUsrMain);
	showWordHistoryInfo();
}

void BrowseWordsWidget::setSkipFinishedCheckBoxVal()
{
	OPT.skipFinishedWords = ui.skipFinishedCheckBox->isChecked();
}
